﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO.Ports;
using System.Threading;

namespace ModbusBase
{
    class Program
    {
        static void Main(string[] args)
        {
            SerialPort serialPort = new SerialPort();

            //设置属性:96N81
            serialPort.PortName = "COM5";
            serialPort.BaudRate = 9600;
            serialPort.Parity = Parity.None;
            serialPort.DataBits = 8;
            serialPort.StopBits = StopBits.One;

            //打开串口
            serialPort.Open();

            while(true)
            {
                Thread.Sleep(2000);
                //拼接报文
                List<byte> sendBtyes = new List<byte>();
                sendBtyes.Add(0x01); //站地址，功能码
                sendBtyes.Add(0x03);
                sendBtyes.Add(0x00);
                sendBtyes.Add(0x00);
                sendBtyes.Add(0x00);
                sendBtyes.Add(0x02);
                //CRC校验
                sendBtyes.Add(0xC4);
                sendBtyes.Add(0x0B);

                //发送报文
                serialPort.Write(sendBtyes.ToArray(), 0, sendBtyes.Count);

                //接收报文
                Thread.Sleep(100); //需要一定的延时

                byte[] receiveBytes = new byte[serialPort.BytesToRead];
                serialPort.Read(receiveBytes, 0, receiveBytes.Length); //接收缓冲区全部的字节

                if (receiveBytes[0] == 0x01) //简单的判断
                {
                    //观察报文： 01  03  04   00  7B  02 4D  4B  7F (原报文16进制)
                    //接收报文： 1   3   4   00  123 2  77  45  127
                    //数据索引： [0] [1] [2] [3] [4] [5] [6] [7] [8]
                    //字节到10进制高低位转换: 123 = (123/256) + (123%256)
                    //                        589 = (589/256) + (589%256)

                    //转换成温度、湿度(1个高字节=256， 所以，高位的要乘以256 + 低位)
                    int humidity = receiveBytes[0] * 256 + receiveBytes[4];
                    int temperature = receiveBytes[5] * 256 + receiveBytes[6];
                    Console.WriteLine($"湿度:{humidity * 0.1}%  温度:{temperature * 0.1}℃");
                }
            }
        }
    }
}
